package com.hx.vending.resolvers;

import com.hx.vending.annotation.CurrentAdminId;
import com.hx.vending.bean.config.Constants;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * Created by Administrator on 2019/3/2.
 */
public class CurrentAdminIdMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (methodParameter.getParameterType().isAssignableFrom(Integer.class) &&
                methodParameter.hasParameterAnnotation(CurrentAdminId.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Object adminId =  nativeWebRequest.getAttribute(Constants.CURRENT_ADMIN_ID, RequestAttributes.SCOPE_REQUEST);
        String u = adminId.toString();
        Integer currentAdminId = Integer.parseInt(u);
        if (null != currentAdminId) {
            return currentAdminId;
        }

        throw new MissingServletRequestPartException(Constants.CURRENT_ADMIN_ID);
    }
}
